﻿using System.Windows.Forms;

namespace RSuite.R4
{
    public class MainForm : AwesomiumForm
    {
        private Package package;

        public MainForm()
            : base("UI/R4.htm")
        {
        }

        protected override void InitForm(Form form)
        {
            form.Text = "R4 - Release";
            form.Icon = new System.Drawing.Icon(@"UI\images\r4.ico");
            form.Width = 400;
            form.Height = 550;
            form.MinimumSize = form.Size;
        }

        protected override object InvokeLocalMethod(string method, dynamic data, string id)
        {
            switch (method)
            {
                case "new":
                    this.package = new Package();
                    return this.package;
                case "open":
                    return this.Open();
                case "save":
                    return this.Save(data);
                case "change-folder":
                    this.package.Input = data;
                    return this.package.CacheItems();
                case "search":
                    return this.package.Search(data["input"], int.Parse(data["limit"]));
                case "pack":
                    this.package.Update(data);
                    return this.package.Pack();
                default:
                    return null;
            }
        }

        private object Open()
        {
            var dialog = new OpenFileDialog();

            if (base.ShowDialog(dialog) != DialogResult.OK)
            {
                return string.Empty;
            }

            this.package = Package.FromFile(dialog.FileName);

            return this.package;
        }

        private object Save(dynamic data)
        {
            if (string.IsNullOrEmpty(this.package.Filename))
            {
                var dialog = new SaveFileDialog();
                if (base.ShowDialog(dialog) != DialogResult.OK)
                {
                    return string.Empty;
                }

                this.package.Update(data);
                this.package.Save(dialog.FileName);
            }
            else
            {
                this.package.Update(data);
                this.package.Save();
            }

            return this.package.Filename;
        }
    }
}